package DataStructrue.stack;


//链栈
public class LinkStack<E> implements MyStack<E>{
    private Node head;//头节点
    private int size;


    private class Node{
        E e;
        Node next;
        public Node(E e, Node next){
            this.e=e;
            this.next=next;
        }
    }

    public LinkStack() {
        head=new Node(null,null);
        size=0;
    }

    @Override
    public E peek() {
        if(isEmpty())
            return null;
        return head.next.e;
    }

    @Override
    public void push(E e) {
        Node tmp=head.next;
        head.next=new Node(e,tmp);
        size++;
    }

    @Override
    public E pop() {
        if(isEmpty())
            return null;
        Node tmp=head.next;
        head.next=tmp.next;
        size--;
        return tmp.e;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    @Override
    public void clear() {
        head=new Node(null,null);
        size=0;
    }

    @Override
    public String toString() {
        StringBuilder sb=new StringBuilder("[");
        if(!isEmpty()){
            Node cur=head.next;
            while(cur!=null){
                sb.append(cur.e).append(",");
                cur=cur.next;
            }
            sb.deleteCharAt(sb.length()-1);
        }
        sb.append("]");
        return "LinkStack{" +
                "head=" + sb +
                ", size=" + size +
                '}';
    }
}
